export class Utils {

    constructor() {

    }

    public static debounce() {
        return () => {

        }
    }

    getMoment() {
        // // 基准宽度，可以根据设计稿自行调整
        // const BASE_WIDTH = 375;
        //
        // // 设计稿中的1rem对应的像素值，通常与基准宽度一致
        // const REM_TO_PX = BASE_WIDTH / 10;
        //
        // // 获取视口宽度
        // const getViewportWidth = () => window.innerWidth || document.documentElement.clientWidth;
        //
        // // 设置rem单位的基准值
        // const setRem = () => {
        //     const viewportWidth = getViewportWidth();
        //     const rem = viewportWidth / REM_TO_PX;
        //     document.documentElement.style.fontSize = `${rem}px`;
        // };
        //
        // // 监听屏幕方向变化事件
        // const handleOrientationChange = () => {
        //     setRem();
        // };
        //
        // // 初始化时设置rem单位的基准值
        // setRem();
        //
        // // 监听窗口大小变化事件
        // window.addEventListener('resize', setRem);
        //
        // // 监听屏幕方向变化事件（部分浏览器可能需要使用"screenorientationchange"）
        // window.addEventListener('orientationchange', handleOrientationChange);
    }

    /**
     * 重置表单数据
     * @param temp
     */
    public static resetTemp(temp: { [props in string]: any }) {
        for (let key in temp) {
            temp[key] instanceof Array ? temp[key] = [] : temp[key] = '';
        }
    }

    /**
     * 验证表单方法
     * @param { Object } temp
     * @param { Object } rules
     * @param { String } single 单独验证字段
     */
    public static validateForm<T, K extends keyof T>(temp: T, rules: { [P in keyof T]?: any }, single?: K): [boolean, string] {
        let isPass: boolean = false, message: string = "";

        if (single) {
            baseValidate(rules[single], temp[single]);
        } else {
            // @ts-ignore
            const keys: K[] = Object.keys(temp);
            for (let i: number = 0; i < keys.length; i++) {
                if (isPass) break;
                const validateRules = rules[keys[i]];
                if (!validateRules) continue;
                baseValidate(validateRules, temp[keys[i]]);
            }
        }

        return [!isPass, message];

        function baseValidate(validateRules: any[], field: any) {
            for (let j: number = 0; j < validateRules.length; j++) {
                if (validateRules[j].required && field.trim() == '') {
                    message = validateRules[j].message;
                    isPass = true;
                    break;
                }
                if (validateRules[j].regexp && !validateRules[j].regexp.test(field)) {
                    message = validateRules[j].message;
                    isPass = true;
                    break;
                }
            }
        }
    }

    /**
     * 权限判断
     * @param value
     */
    public static getPermission(value: string[] = []): boolean {
        return value.some((item: string) => {
            //return store.getters.roles.includes(item);
            console.log(item);
        })
    }

    /**
     * 根据状态值获取数组对应的键值对数据
     * @param status
     * @param arr
     * @param key
     */
    public static getStatus<T, K extends keyof T>(status: any, arr: T[], key?: K) {
        let data: T | {  desc: string, code: number, className: string };
        let not_data = {
            desc: '-',
            code: -1,
            className: ''
        }
        if (arr && arr.length) {
            let field: any = key ? key : 'code';
            let index: number = arr.findIndex((item: any) => item[field] == status);
            !~index ? (data = not_data) : (data = arr[index]);
        } else {
            data = not_data;
        }
        return data
    }

    /**
     * 处理IOS 小程序base64图片分享问题
     * @param base64data
     */
    public static async base64ToBuffer(base64data: string) {
        const [, format, bodyData] = new RegExp(/data:image\/(\w+);base64,(.*)/).exec(base64data) || [];

        if (!format) return new Error('ERROR_BASE64SRC_PARSE');

        const FILE_BASE_NAME: number = new Date().getTime();

        const wx: any = {};
        // wx端
        const filePath = `${ wx.env.USER_DATA_PATH }/${ FILE_BASE_NAME }.${ format }`;

        const buffer: any = wx.base64ToArrayBuffer(bodyData);

        const fsm = wx.getFileSystemManager();

        return new Promise((resolve, reject) => {
            fsm.writeFile({
                filePath,
                data: buffer,
                encoding: 'binary',
                success() {
                    resolve(filePath);
                },
                fail() {
                    reject(base64data);
                }
            });
        });
    }

    /**
     * 获取模块路径
     * @param module_list
     * @param sort
     */
    public static getModulesPath(module_list: { [key: string]: any }, sort: string[] = []) {
        let list: any = [], keys = Object.keys(module_list);
        if (!sort.length) return keys;
        sort.forEach((item) => {
            const current = keys.find((key) => key.includes(item));
            list.push(current);
        });
        return list;
    }

    /**
     * 获取模块
     * @param module_list
     */
    public static async getModules(module_list: { [key: string]: any }) {
        let obj: any = {}, keys = Object.keys(module_list);
        await keys.reduce(async (pre: any, curr_star: string) => {
            const key: string = curr_star.replace(/(\.\/modules\/|\.ts)/g, '');
            const res = await module_list[curr_star]();
            obj[key] = res.default;
            return pre;
        }, {});
        return obj;
    }

    /**
     * 获取设备信息
     * @return is_android 是否是安卓
     * @return is_ios 是否是苹果
     * @return is_mobile 是否是手机
     */
    public static getSystem(): { is_android: boolean, is_ios: boolean, is_mobile: boolean } {
        let info: string = navigator.userAgent;
        let is_android = info.indexOf('Android') > -1 || info.indexOf('Adr') > -1; //android终端
        let is_ios = !!info.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        let is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(info);

        return {
            is_android,
            is_ios,
            is_mobile
        }
    }

    /**
     * 监听页面元素
     */
    public static setIntersectionObserve() {
        return new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
            entries.forEach((entry: any) => {
                if (entry.isIntersecting) {
                    entry.target.classList.add(entry.target.dataset.active || "scroll-animate");
                } else {
                    entry.target.classList.remove(entry.target.dataset.active || "scroll-animate");
                }
            })
        });
    }

    /**
     * 获取浏览器信息
     * @return { 'MicroMessenger' | 'Chrome' | 'Opera' | 'Firefox' | 'Safari' | 'QQ' | string }
     */
    public static getBrowserInfo(): 'MicroMessenger' | 'Chrome' | 'Opera' | 'Firefox' | 'Safari' | 'QQ' | string {
        let userAgent: any = navigator.userAgent;
        //微信内置浏览器
        if(userAgent.match(/MicroMessenger/i) == 'MicroMessenger') {
            return "MicroMessenger";
        }
        //Chrome
        else if(userAgent.match(/Chrome/i) == 'Chrome') {
            return "Chrome";
        }
        //Opera
        else if(userAgent.match(/Opera/i) == 'Opera') {
            return "Opera";
        }
        //Firefox
        else if(userAgent.match(/Firefox/i) == 'Firefox') {
            return "Firefox";
        }
        //Safari
        else if(userAgent.match(/Safari/i) == 'Safari') {
            return "Safari";
        }
        //QQ内置浏览器
        else if(userAgent.match(/QQ/i) == 'QQ') {
            return "QQ";
        }
        else {
            return "未定义:" + userAgent;
        }
    }
}